﻿Imports ComponentFactory.Krypton.Toolkit
Imports System.Data.OleDb

Public Class EditorDeTabelaSimples
    Inherits KryptonForm

    Private conexao As OleDbConnection
    Private cmdBuilder As OleDbCommandBuilder
    Private dataAdapter As OleDbDataAdapter
    Private dataSet As DataSet
    Private tabela As String
    Private campo As String

    Sub New(ByVal titulo As String, ByRef conexao As OleDb.OleDbConnection, ByVal nomeTabela As String, ByVal nomeCampo As String)

        ' This call is required by the Windows Form Designer.
        InitializeComponent()
        ' Add any initialization after the InitializeComponent() call.

        Me.Text = titulo
        Me.conexao = conexao
        tabela = nomeTabela
        campo = nomeCampo

        Try
            Dim cmd As String = String.Format("SELECT * FROM {0}", tabela)
            dataAdapter = New OleDbDataAdapter(cmd, conexao)
            dataSet = New DataSet()
            dataAdapter.Fill(dataSet, tabela)
            cmdBuilder = New OleDbCommandBuilder(dataAdapter)
            cmdBuilder.ConflictOption = ConflictOption.OverwriteChanges
            lbItens.DataSource = dataSet.Tables(tabela)
            lbItens.DisplayMember = campo
        Catch ex As OleDbException
            Debug.WriteLine("Erro: " & ex.Message)
        End Try

    End Sub

    Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click

        Dim vetor(lbItens.Items.Count - 1) As String
        For i = 0 To lbItens.Items.Count - 1
            vetor(i) = DirectCast(lbItens.Items(i), DataRowView).Item(campo)
        Next

        If Not (String.IsNullOrEmpty(txtItem.Text)) And Not (Assistente.verificarExistencia(txtItem.Text, vetor)) Then
            Try
                Dim r As DataRow = dataSet.Tables(tabela).NewRow()
                r.BeginEdit()
                r.Item(campo) = txtItem.Text
                r.EndEdit()
                dataSet.Tables(tabela).Rows.Add(r)
                lbItens.SelectedIndex = lbItens.Items.Count - 1

                txtItem.Clear()
                txtItem.Focus()

            Catch ex As OleDbException
                Debug.WriteLine(ex.Message)
            End Try
        End If
    End Sub

    Private Sub btnDel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDel.Click
        Try
            If (lbItens.SelectedItem IsNot Nothing) Then
                dataSet.Tables(tabela).Rows(lbItens.SelectedIndex).Delete()
            End If
        Catch ex As OleDbException
            Debug.WriteLine(ex.Message)
        End Try
    End Sub

    Private Sub btnOk_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOk.Click
        dataAdapter.Update(dataSet, tabela)
        Me.Dispose()
    End Sub
End Class